<template>
  <div class="container">
    <a-card class="general-card" title="需求详情">
      <a-steps :current="1">
        <a-step description="选择用户">创建/选择用户</a-step>
      </a-steps>
      <ProTable :columns="columns" :request="fetchUserList" row-key="id" :action-ref="setActionRef"
        :pagination="false"
      >
        <template #operations="{ record }">
          <a-button type="text" @click="selectUser(record)">选择</a-button>
        </template>
      </ProTable>
      <!-- <a-button type="primary" @click="entering">手动录入客户</a-button> -->

      <a-form style="margin-top: 10px;" :model="detailForm" ref="detailFormRef" layout="vertical">
        <div>
          <a-row :gutter="24">
            <a-col :span="6">
              <a-form-item label="需求人姓名" field="demandPersonName" :rules="[{ required: true, validator:validateNotNumber }]">
                <a-input  v-model="detailForm.demandPersonName" placeholder="请输入需求人姓名"
         />
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item label="需求人联系电话" field="demandPersonPhone" :rules="[{ required: true, validator:validatePhoneNumber }]">
                <a-input :input-attrs="{type: 'phone'}" disabled @change="getList" v-model="detailForm.demandPersonPhone" placeholder="请输入需求人联系电话" />
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item label="座机号码">
                <a-input v-model="detailForm.demandPersonLandlinePhone" placeholder="请输入座机号码" />
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item label="用户标签">
                <a-tree-select placeholder="请选择用户标签" :field-names="{ key: 'id', title: 'name' }"
                  v-model="detailForm.demandPersonTag" multiple :data="tagList">
                </a-tree-select>
              </a-form-item>
            </a-col>
          </a-row>

          <!-- <a-form-item label="省市区">
          <AddressSelect v-model="detailForm.demandAddress" />
        </a-form-item> -->
          <a-form-item label="详细地址">
            <a-textarea v-model="detailForm.demandPersonAddress" placeholder="请输入详细地址" />
          </a-form-item>
        </div>


        <a-steps :current="1" style="margin-top: 20px;">
          <a-step description="填写需求记录">
            预约服务
            <template #icon>
              <icon-steps>2 </icon-steps>
            </template>
          </a-step>
        </a-steps>
       

        <a-row :gutter="24">
          <a-col :span="8">
            <a-form-item label="需求类型" field="typeId" :rules="[{ required: true, message: '请选择需求类型' }]">
              <a-tree-select v-model="detailForm.typeId" :field-names="{ key: 'id', title: 'name' }" placeholder="请选择需求类型"
                :data="requisitionTypeList">
              </a-tree-select>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="需求单渠道" field="channelId" :rules="[{ required: true, message: '请选择需求单渠道' }]">
              <a-tree-select v-model="detailForm.channelId" :field-names="{ key: 'id', title: 'name' }"
                placeholder="需求单渠道" :data="serviceTypeList">
              </a-tree-select>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="四级分类" field="fourTypeId" :rules="[{ required: true, message: '请选择四级分类' }]">
              <a-tree-select     :allow-clear="true"    :filter-tree-node="filterTreeNode" v-model="detailForm.fourTypeId" :field-names="{ key: 'id', title: 'name' }" :allow-search="true" :selectable="selectable" placeholder="请选择"
                :data="fourTypeList">
              </a-tree-select>
            </a-form-item>
          </a-col>
        </a-row>
         <!-- 顶部部分 -->
         <h2>选择预约服务 <a-button type="primary" @click="() => isServerer = !isServerer">选择服务</a-button> </h2>
        <ServiceReservation v-if="isServerer" v-model="serviceReservationData" />
        <div v-if="isServerer">
          <h2>填写联系人信息 <a-button @click="handleSync" type="primary"> 同步需求人信息 </a-button> </h2>
          <a-row :gutter="24">
            <a-col :span="6">
              <a-form-item field="contactName" label="联系人信息" :rules="[{ required: true, message: '联系人信息' }]">
                <a-input v-model="detailForm.contactName" placeholder="联系人" />
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item field="contactPhone" label="联系人电话" :rules="[{  type: 'string',
                required: true,
                match: /^1[3456789]\d{9}$/,
                message: '请输入有效的手机号', }]">
                <a-input  v-model="detailForm.contactPhone" placeholder="电话" />
              </a-form-item>
            </a-col>
          </a-row>
        <a-row :gutter="24">
          <a-col :span="12">
              <!-- 服务地址 -->
            <a-form-item label="省市区" field="address" required>
            <AddressSelect v-model="detailForm.address" />
          </a-form-item>
          </a-col>
          <a-col :span="12" v-if="serviceReservationData.productType === 2">
              <!-- 服务地址 -->
              <a-form-item label="省市区">
              <AddressSelect v-model="detailForm.moveAddress" />
            </a-form-item>
          </a-col>
        </a-row>
                  
           
          <a-row :gutter="24">
            <a-col :span="12">
              <a-form-item field="contactAddress" :rules="[{ required: true, message: '详细地址' }]" :label=" serviceReservationData.productType === 2 ? '搬出地址':'详细地址'">
                <a-textarea :rows="4" v-model="detailForm.contactAddress" placeholder="详细地址" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-row v-if="serviceReservationData.productType === 2">
                <a-form-item label="搬入地址">
                  <a-textarea v-model="detailForm.enterAddress" placeholder="搬家地址" />
                </a-form-item>
              </a-row>
            </a-col>
          </a-row>
          <!-- <a-space v-if="serviceReservationData.productType === 2">
            <a-form-item label="省市区">
              <AddressSelect v-model="detailForm.moveAddress" />
            </a-form-item>
          </a-space> -->
    
  


          <!-- 预约日期 -->
          <a-row>
            <a-col :span="12">
              <a-form-item label="预约日期" field="reservationTime" :rules="[{ required: true, message: '请选择预约日期' }]">
                <a-date-picker show-time v-model="detailForm.reservationTime" format="YYYY-MM-DD HH:mm" :disabledDate="(current) => dayjs(current).isBefore(dayjs().add(-1, 'day'))" />
              </a-form-item>
            </a-col>
          </a-row>

        </div>
        <a-form-item label="需求记录" field="requirementRecord" :rules="[{ required: true, message: '请输入需求记录' }]">
          <a-textarea :rows="4" v-model="detailForm.requirementRecord" placeholder="需求记录"  />
        </a-form-item>

        <!-- 上传需求记录 -->
        <a-form-item label="上传需求附件">
          <UploadFile v-model="detailForm.fileList"></UploadFile>
        </a-form-item>
        <!-- <a-form-item label="注意事项">
          <a-textarea :toolbar="[]" v-model="detailForm.carefulRemark" placeholder="请填写注意事项" :plugins="[]" />
        </a-form-item> -->


        <!-- 操作按钮 -->

        <a-form-item>
          <a-button type="primary" @click="handleSave(1)">提交并跟进</a-button>
          <a-button type="primary" @click="handleSave(3)" style="margin-left: 10px">提交并完成</a-button>
          <a-button @click="handleCancel" style="margin-left: 10px">取消</a-button>
        </a-form-item>
      </a-form>
      <tabList ref="refTableList" :username="detailForm.demandPersonPhone" :address="detailForm.demandPersonAddress">
      </tabList>
      <Modal v-model:visible="visible" title="添加用户信息" :width="800" @before-ok="handleAddUser">
        <a-form :model="detailForm" ref="userFormRef" layout="vertical">
          <a-row :gutter="24">
            <a-col :span="12">
              <a-form-item field="demandPersonName" label="需求人姓名" :rules="[{ required: true, validator:validateNotNumber }]">
                <a-input  v-model="detailForm.demandPersonName" placeholder="请输入需求人姓名"
                  />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item field="demandPersonPhone" label="需求人联系电话"  :rules="[{ required: true, validator:validatePhoneNumber }]">
                <a-input  @change="getList" v-model="detailForm.demandPersonPhone" placeholder="请输入需求人联系电话"
                  />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="座机号码" field="demandPersonLandlinePhone">
                <a-input  v-model="detailForm.demandPersonLandlinePhone" placeholder="请输入座机号码"
                  />
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </Modal>
    </a-card>
  </div>
</template>
<script setup lang="ts">
import { ref, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import { saveDemand, getDemandDetail, areaCodeGetList } from "@/api/demand"; // 
import { getSpecTreeList, getServiceListNoPage, getProjectList, getPrice } from "@/api/service";
import { getTagList } from "@/api/tag";
import { getFourTypeList } from "@/api/foutType";
import AddressSelect from "@/components/AddressSelect/index.vue";
import tabList from "@/components/TabList/index.vue"
import ServiceReservation from '@/components/ServiceSelection/index.vue'; // 
import Message from "@arco-design/web-vue/es/message";
import { Modal } from "@arco-design/web-vue";
import dayjs from 'dayjs'
import UploadFile from '@/components/FileUpload/index.vue';
const visible = ref(false);
const refTableList = ref<InstanceType<typeof tabList> | null>(null);
const provinceList = ref<{ value: string; label: string }[]>([]);
const tagList = ref([]);
const requisitionTypeList = ref([]);
const serviceTypeList = ref([]);
const fourTypeList = ref([])
const isServerer = ref(false);
const route = useRoute();
const router = useRouter();
const detailFormRef = ref()
const userFormRef = ref();
const validatePhoneNumber = ( value, callback) => {
  console.log(value)
  if (!value || /^1[3456789]\d{9}$/.test(value)) {
    callback();
  } else {
    callback('请输入有效的手机号码');
  }
};

const validateNotNumber = (value, callback) => {
  if (value && !/\d/.test(value)) {
    callback();
  } else {
    callback('姓名不允许输入数字');
  }
};
const selectable = (node, level) => {
      // 只有三级节点是可选的
      return level.level === 3;
    };

    const  filterTreeNode = (searchValue, nodeData)=> {
        return nodeData.name.toLowerCase().indexOf(searchValue.toLowerCase()) > -1;
      }
onMounted(async () => {
  const res = await areaCodeGetList('');
  provinceList.value = res.data.map(item => ({ value: item.code, label: item.name }));

  const list = await getTagList({ type: 3 });
  tagList.value = list.data

  // 需求类型
  const res1 = await getTagList({ type: 1 });
  requisitionTypeList.value = res1.data
  // 需求单渠道
  const res2 = await getTagList({ type: 2 });
  serviceTypeList.value = res2.data

  // 四级分类
  const res3 = await getFourTypeList(1, 1000, '',0);
  fourTypeList.value = res3.data

});


const serviceReservationData = ref({
  productType: 0,
  service: "",
  chargeType: 0,
  productList: [],
});
const getList = async () => {
  refTableList.value?.refresh();

};


// 服务
const service = ref("");
const detailForm = ref({
  id: null, // 需求单ID，修改时必传
  demandPersonName: "", // 需求人姓名
  demandPersonPhone: "", // 需求人手机号
  demandPersonLandlinePhone: "", // 需求人座机
  demandPersonTag: [], // 需求人用户标签
  demandPersonProvince: "", // 需求人省份
  demandPersonCity: "", // 需求人城市
  demandPersonCounty: "", // 需求人区县
  demandPersonAddress: "", // 需求人详细地址
  address: { province: "", provinceLabel: "", city: "", cityLabel: "", county: "", countyLabel: "" }, // 省市区
  demandAddress: { province: "", provinceLabel: "", city: "", cityLabel: "", county: "", countyLabel: "" },
  moveAddress: { province: "", provinceLabel: "", city: "", cityLabel: "", county: "", countyLabel: "" },
  typeId: "", // 需求单类型ID
  typeName: "分类名称", // 需求单类型名称
  channelId: "", // 需求单渠道ID
  channelName: "", // 需求单渠道名称
  fourTypeId: "", // 四级分类ID
  fourTypeName: "", // 四级分类名称
  contactName: "", // 联系人姓名
  contactPhone: "", // 联系人手机号
  contactProvince: "", // 联系人省份
  contactCity: "", // 联系人城市
  contactCounty: "", // 联系人区县
  contactAddress: "", // 联系人详细地址
  reservationTime: "", // 预约时间
  productType: 0, // 服务产品类型 1保洁 2搬家 3保养 4维修
  chargeType: 0, // 收费类型 1面单订单 2内部员工 3家装订单 4保内 5保外
  requirementRecord: "", // 需求记录
  demandStatus: "2", // 2提交并跟进 4 提交并完成
  enterProvince: "", // 搬进地址省份
  enterCity: "", // 搬进地址城市
  enterCounty: "", // 搬进地址区县
  enterAddress: "", // 搬进地址详细地址
  carefulRemark: "", // 注意事项
  productList: [] as any[], // 服务产品列表
  fileList: [] as any[], // 文件列表
  intentionState: "",
  signState: "",
  cid: ""
});

const userForm = ref({
  name: "",
  phone: "",
  landlinePhone: "",
  address: "",
  tags: [] as string[],
});
const handleUploadSuccess = (fileItem: any) => {
  const response = fileItem.response;
  const url = response.data.url;
  console.log(detailForm.value, '---')
  // detailForm.value.fileList.push()
  // return response.data.url;
}
const productList = ref([]);
const getProductList = async () => {
  const res: any = await getServiceListNoPage(detailForm.value.productType);
  console.log(res, '--规格')
  productList.value = res.data;
};
let showUserForm = ref(false);
const entering = () => {
  showUserForm.value = !showUserForm.value;
};

const columns = [
  { title: '项目编号', dataIndex: 'id', key: 'id', hideInSearch: true },
  { title: 'CID', dataIndex: 'cid', key: 'cid', hideInSearch: true },
  { title: '姓名', dataIndex: 'customName', key: 'customName', hideInSearch: true },
  { title: '手机号', dataIndex: 'phone', key: 'typeName', hideInTable: true },
  { title: '手机号', dataIndex: 'phoneNumber', key: 'phoneNumber', hideInSearch: true },
  { title: '项目地址', dataIndex: 'address', key: 'typeName', hideInTable: true },
  { title: '项目地址', dataIndex: 'address', key: 'typeName', hideInSearch: true },
  { title: '操作', dataIndex: 'operations', slotName: 'operations', hideInSearch: true }
];

const table_columns = [
  { title: "规格名称", dataIndex: "name", hideInSearch: true, slotName: 'name' },
  { title: "数量", dataIndex: "num", hideInSearch: true, slotName: 'num' },
  { title: "单价/元", dataIndex: "price", hideInSearch: true, slotName: 'price' },
  { title: "总价/元", dataIndex: "sumPrice", hideInSearch: true, slotName: 'sumPrice' },
  { title: "操作", dataIndex: "operation", hideInSearch: true, slotName: "operation" },
];
const actionRef = ref();

// 初始化表单数据
onMounted(async () => {
  const id = route.params.id;
  console.log(id, 'id')
  getProductList()
  if (id !== '0') {
    const response = await getDemandDetail(id);
    if (response) {
      console.log(response, 'response')
      Object.assign(detailForm.value, response);
      Object.assign(serviceReservationData.value, response);
    } else {
      console.error("获取需求详情失败", response.message);
    }
  } else {
    // 如果是新建需求单，初始化表单数据
    detailForm.value = {
      id: null,
      demandPersonName: "",
      demandPersonPhone: "",
      demandPersonLandlinePhone: "",
      demandPersonTag: [],
      demandPersonProvince: "",
      demandPersonCity: "",
      demandPersonCounty: "",
      demandPersonAddress: "",
      typeId: "",
      typeName: "",
      channelId: "",
      channelName: "",
      fourTypeId: "",
      fourTypeName: "",
      contactName: "",
      contactPhone: "",
      contactProvince: "",
      contactCity: "",
      contactCounty: "",
      contactAddress: "",
      reservationTime: "",
      productType: 0,
      chargeType: 1,
      requirementRecord: "",
      demandStatus: "2",
      enterProvince: "",
      enterCity: "",
      enterCounty: "",
      enterAddress: "",
      carefulRemark: "",
      address: { province: "", provinceLabel: "", city: "", cityLabel: "", county: "", countyLabel: "" }, // 省市区
      demandAddress: { province: "", provinceLabel: "", city: "", cityLabel: "", county: "", countyLabel: "" },
      moveAddress: { province: "", provinceLabel: "", city: "", cityLabel: "", county: "", countyLabel: "" },
      productList: [],
      fileList: [] as any[],
      intentionState: "",
      signState: "",
      cid: ""
    };
  }
});

const handleSync = () => {
  detailForm.value.contactName = detailForm.value.demandPersonName
  detailForm.value.contactPhone = detailForm.value.demandPersonPhone
  detailForm.value.contactAddress = detailForm.value.demandAddress.provinceLabel + detailForm.value.demandAddress.cityLabel + detailForm.value.demandAddress.countyLabel + detailForm.value.demandPersonAddress
}

// 上传文件

// 保存需求单
const handleSave = async (demandStatus) => {
  try {
    const err = await detailFormRef.value.validate();
    if (!detailForm.value.demandPersonPhone) {
      Message.warning('请填写需求人电话')
      return
    }
    if (!err) {

      const data = {
        ...detailForm.value,
        ...serviceReservationData.value,
        demandPersonTag: detailForm.value.demandPersonTag ? detailForm.value.demandPersonTag.join(',') : '',
        demandStatus: demandStatus,
        "enterProvinceCode": detailForm.value.moveAddress.province,//搬进地址省份CODE
        "enterCityCode": detailForm.value.moveAddress.city,//搬进地址城市CODE
        "enterCountyCode": detailForm.value.moveAddress.county,//搬进地址区县CODE

        "enterProvince": detailForm.value.moveAddress.provinceLabel,//搬进地址省份
        "enterCity": detailForm.value.moveAddress.cityLabel,//搬进地址城市
        "enterCounty": detailForm.value.moveAddress.countyLabel,//搬进地址区县


        "demandPersonProvinceCode": detailForm.value.demandAddress.province,//需求人省份CODE
        "demandPersonCityCode": detailForm.value.demandAddress.city,//需求人城市CODE
        "demandPersonCountyCode": detailForm.value.demandAddress.county,//需求人区县COD
        "demandPersonProvince": detailForm.value.demandAddress.provinceLabel,//需求人省份
        "demandPersonCity": detailForm.value.demandAddress.cityLabel,//需求人城市
        "demandPersonCounty": detailForm.value.demandAddress.countyLabel,//需求人区县


        "contactProvinceCode": detailForm.value.address.province,//联系人省份CODE
        "contactCityCode": detailForm.value.address.city,//联系人城市CODE
        "contactCountyCode": detailForm.value.address.county,//联系人区县CODE
        "contactProvince": detailForm.value.address.provinceLabel,//联系人省份
        "contactCity": detailForm.value.address.cityLabel,//联系人城市
        "contactCounty": detailForm.value.address.countyLabel,//联系人区县

      }
      if(isServerer.value){
        if(data.productList.length===0){
          Message.warning('请添加产品')
          return
        }
      }
      console.log(data, 'data')
      const response = await saveDemand(data);
      if ((response as { success: boolean }).success) {
        console.log("保存需求成功");
        router.push({ name: "requirement" }); // 跳转到需求单列表页面
      } else {
        console.error("保存需求失败", response);
      }
    }
    // 继续保存逻辑
  } catch (error) {
    console.error('表单校验失败', error);
  }

};

// 取消编辑
const handleCancel = () => {
  router.push({ name: "requirement" }); // 跳转到需求单列表页面
};


const fetchUserList = async (params) => {
  console.log(params)
  if (!params.phone && !params.address) {
    return {
      data: [],
      success: true,
    }
  } else {
    const response = await getProjectList(params);
    if (response.data.length === 0) {
      Modal.confirm({
        title: '创建用户',
        content: '系统暂无法找到用户，请问是否创建新用户？',
        onOk: async () => {
          detailForm.value.demandPersonPhone = params.phone
          visible.value =true
          
        },
        okText: '创建',
      });
    }
    return response
  }

};

const selectUser = (record) => {
  const user = { ...record }
  console.log(user)
  detailForm.value.intentionState = user.intentionState
  detailForm.value.signState = user.signState
  detailForm.value.cid = user.cid
  detailForm.value.demandPersonName = user.customName
  detailForm.value.demandPersonPhone = user.phoneNumber
  detailForm.value.demandPersonAddress = user.address
  detailForm.value.contactName = user.customName
  detailForm.value.contactPhone = user.phoneNumber
  detailForm.value.contactAddress = user.address
};

const setActionRef = (ref) => {
  actionRef.value = ref;
};

const handleAddUser = async ()=>{
  const err = await  userFormRef.value.validate()
  if(err){
    return false;
  }else {
    return true
  }
}
</script>

<style scoped lang="less">
.container {
  padding: 20px;
}
</style>

<style scoped lang="less">.container {
  padding: 20px;
}</style>